package app.foodnote;
import java.util.List;


import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class LocationActivity extends MapActivity  {
	PlacesList nearPlaces;
	MapView mapView;
	GooglePlaces googlePlaces;
	// Map overlay items
	List<Overlay> mapOverlays;
	
	//AddItemizedOverlay itemizedOverlay;
	GeoPoint geoPoint1;
	GeoPoint geoPoint2;
	
	// Map controller
	MapController mc;
	
	ProgressDialog pDialog;
	
	double latitude;
    double longitude;
	OverlayItem overlayItem;

	double latExtra;
	double logExtra;
	
	SimpleItemizedOverlay itemizedOverlay;
	SimpleItemizedOverlay itemizedOverlay2;
	
	Bundle bundle;
	@Override
	 public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        requestWindowFeature(Window.FEATURE_NO_TITLE);
	        setContentView(R.layout.form_map);
	        
	        bundle = savedInstanceState;
	        
	        Intent i = getIntent();
	        mapView = (MapView) findViewById(R.id.mapview);
	        mapView.setBuiltInZoomControls(true);
	        mapView.getController().setZoom(17);
	        mapView.displayZoomControls(true);
	        
	        latExtra = i.getExtras().getDouble("LAT_EXTRA");
	        logExtra = i.getExtras().getDouble("LOG_EXTRA");
	        
	        new LoadPlaces().execute(latExtra, logExtra);
	        //nearPlaces = (PlacesList) i.getSerializableExtra("NEAR_PLACES");
	        
	       
	       
	 }
	class LoadPlaces extends AsyncTask<Double, String, String>{
		double lat;
		double lon;

	 @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(LocationActivity.this);
            pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading ..."));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
	 	/*public void execute(double latExtra, double logExtra,
			Bundle savedInstanceState) {
			this.lat = latExtra;
			this.lon = logExtra;
			this.bundle = savedInstanceState;
			
		}*/
		@Override
		protected String doInBackground(Double... params) {
			double lAT_EXTRA = params[0];
			double lOG_EXTRA = params[1];
			googlePlaces = new GooglePlaces();
			//PlacesList places = null;
			try {
				String types = "cafe|food|restaurant"; // Listing places only cafes, restaurants, foods restaurant|
				 
                // Radius in meters - increase this value if you don't find any places
                double radius = 1000;
				nearPlaces = googlePlaces.search(lAT_EXTRA, lOG_EXTRA, radius, types);
				
			} catch(Exception e){
				e.printStackTrace();
			}
			return null;
		}
		protected void onPostExecute(String file_url) {
	        // dismiss the dialog after getting all products
	        pDialog.dismiss();
	        
	        runOnUiThread(new Runnable() {
				
				public void run() {
					if(nearPlaces.results == null){
					 	mapOverlays = mapView.getOverlays();
				        
				        geoPoint1 = new GeoPoint((int) (latExtra * 1E6), (int) (logExtra * 1E6));
				        Drawable marker = getResources().getDrawable(R.drawable.mark_red);
				        /*itemizedOverlay = new AddItemizedOverlay(marker);*/
				        itemizedOverlay = new SimpleItemizedOverlay(marker, mapView); // new add
				        MapController mapController = mapView.getController();
				        mapController.setCenter(geoPoint1);
				        
				        // Map overlay item
				        overlayItem = new OverlayItem(geoPoint1, "Vị trí món ăn", "Đây là vị trí cần tìm");
				        itemizedOverlay.addOverlay(overlayItem);
				        mapOverlays.add(itemizedOverlay);
				        /*itemizedOverlay.populateNow();*/
					}
					else {
						mapOverlays = mapView.getOverlays();
				        
				        geoPoint1 = new GeoPoint((int) (latExtra * 1E6), (int) (logExtra * 1E6));
				        Drawable marker = getResources().getDrawable(R.drawable.mark_red);
				        /*itemizedOverlay = new AddItemizedOverlay(marker);*/
				        itemizedOverlay = new SimpleItemizedOverlay(marker, mapView);

				        
				        // Map overlay item
				        overlayItem = new OverlayItem(geoPoint1, "Vị trí món ăn", "Đây là vị trí cần tìm");
				        itemizedOverlay.addOverlay(overlayItem);
				        mapOverlays.add(itemizedOverlay);
				        /*itemizedOverlay.populateNow();*/
				        
				        // Drawable marker icon
				        Drawable drawble = getResources().getDrawable(R.drawable.mark_blue);
				        /*itemizedOverlay = new AddItemizedOverlay(drawble);*/
				        itemizedOverlay2 = new SimpleItemizedOverlay(drawble, mapView);
				        
				        mc = mapView.getController();
				        
				        
				        // These values are used to get map boundary area
				        // The area where you can see all the markers on screen
				        int minLat = Integer.MAX_VALUE;
				        int minLong = Integer.MAX_VALUE;
				        int maxLat = Integer.MIN_VALUE;
				        int maxLong = Integer.MIN_VALUE;
				        
				        /*if(nearPlaces.results != null){*/
				        	for(Place place : nearPlaces.results){
				        		latitude = place.geometry.location.lat;
				        		longitude = place.geometry.location.lng;
				        		
				        		geoPoint2 = new GeoPoint((int) (latitude * 1E6), (int) (longitude * 1E6));
				        		overlayItem = new OverlayItem(geoPoint2, place.name, place.vicinity);
				        		itemizedOverlay2.addOverlay(overlayItem);
				        		
				        		// calculating map boundary area
				                minLat  = (int) Math.min( geoPoint2.getLatitudeE6(), minLat );
				                minLong = (int) Math.min( geoPoint2.getLongitudeE6(), minLong);
				                maxLat  = (int) Math.max( geoPoint2.getLatitudeE6(), maxLat );
				                maxLong = (int) Math.max( geoPoint2.getLongitudeE6(), maxLong );
				        	}
				        	mapOverlays.add(itemizedOverlay2);
				        	
				        	// showing all overlay items
				        	/*itemizedOverlay.populateNow();*/
				        /*}*/
				        // Adjusting the zoom level so that you can see all the markers on map
				        mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
				 
				        // Showing the center of the map
				        mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
				        mapView.postInvalidate();
				        
				        if (bundle == null) {
							
							final MapController mc = mapView.getController();
							mc.animateTo(geoPoint1);
							mc.setZoom(16);
							
						} else {
							
							// example restoring focused state of overlays
							int focused;
							focused = bundle.getInt("focused_1", -1);
							if (focused >= 0) {
								itemizedOverlay.setFocus(itemizedOverlay.getItem(focused));
							}
							focused = bundle.getInt("focused_2", -1);
							if (focused >= 0) {
								itemizedOverlay2.setFocus(itemizedOverlay2.getItem(focused));
							}
							
						}
					
				}
				}
			});
		}
		
	}
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		
		// example saving focused state of overlays
		if (itemizedOverlay.getFocus() != null) outState.putInt("focused_1", itemizedOverlay.getLastFocusedIndex());
		if (itemizedOverlay2.getFocus() != null) outState.putInt("focused_2", itemizedOverlay2.getLastFocusedIndex());
		super.onSaveInstanceState(outState);
	
	}

	/*@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 1, "Remove Overlay");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == 0) {
			
			// example hiding balloon before removing overlay
			if (itemizedOverlay.getFocus() != null) {
				itemizedOverlay.hideBalloon();
			}
			mapOverlays.remove(itemizedOverlay);
			mapView.invalidate();
			
		}
		return true;
	}*/
	 public boolean onCreateOptionsMenu(Menu menu) {
			new MenuInflater(this).inflate(R.menu.menu_show_place_list_and_map, menu);
			//setMenuBackground(); 
			return (super.onCreateOptionsMenu(menu));
		}
		
		@Override
		public boolean onOptionsItemSelected(MenuItem item){
			if(item.getItemId()==R.id.back){
				startActivity(new Intent(LocationActivity.this, FoodPlaces.class));
				return true;
			}
			return (super.onOptionsItemSelected(item));
			
		}
}
